<?php

class Controller_User extends Controller_Site {

	public function before() {
		parent::before();
		// load config account types
		Config::load('account_types', true);
	}

	public function action_index() {
		if (!Session::get('user_id')) {
			Response::redirect('login');
		}
	}

	public function action_login() {
		// submit login
		if (Input::is_ajax() && Input::method() == 'POST') {
			if (Lib\Auth::login(Input::post('username'), Input::post('password'))) {
				$url = Session::get('url');
				if (!empty($url)) {
					Lib\Response::json(array('redirect' => $url));
				}

				Lib\Response::json(array('redirect' => Uri::create('/')));
			}
			else {
				Lib\Response::json(array(
					'alert' => Lib\Message::error('Wrong username or password'),
					'callback' => "(function($){
							$('input[name=username], input[name=password]').val('');
						})(jQuery);"
				), true);
			}
		}

		// set vars
		$this->set('genders', \Model_Gender::find('all'));
		$this->set('security_questions', \Model_Security_Question::find('all'));
	}

	public function action_logout() {
		Lib\Auth::logout();
		Response::redirect('/');
	}

	public function action_forgot_password() {
		// submit data
		if (Input::is_ajax() && Input::method() == 'POST') {
			$email = Input::post('email');
			if (count(Model_User::find_by_email($email))) {
				// data
				$data = array('code' => Helper\String::random_string('alnum', 10));
				// send mail
				DB::insert('cron_emails')->set(array(
					'subject' => 'Reset my password',
					'body' => View::forge('user/email_template/forgot_password', $data)->render(),
					'from_email' => Config::get('setting.email_from'),
					'from_name' => Config::get('setting.email_name'),
					'to_email' => $email,
					'to_name' => $email,
					'created_at' => DB::expr('NOW()')
				))->execute();

				//redirect to homepage
				Lib\Response::json(array('redirect' => Uri::base(true)), true);
			}
			else {
				Lib\Response::json(array('alert' => Lib\Message::error('Email is does not exists in system. Please try again.')), true);
			}
		}
	}

	public function action_activate() {
		$code = Input::get('code');
		$email = Input::get('email');

		$user = Model_User::find(array('where' => array(
				'code_activate' => $code,
				'email' => $email
			)));

		if (!$user) {
			$this->set('message', Lib\Message::error('Code activate does not exists. Please check again.'));
		}

		if (strtotime($user->code_activate_expired) < time()) {
			$this->set('message', Lib\Message::error('Code activate has expired.'));
		}

		$user->status = 'ACTIVED';
		if ($user->save()) {
			$this->set('message', Lib\Message::success('Your account is actived.'));
		}
	}

}
